package embyparse.noobparser;

import java.util.ArrayList;

import embyparse.parsetree.ParseNode;

/**
 * The matcher performs one round of LR parsing on the stack of tokens given to it.
 * @author Justin
 *
 */
public class Matcher {

	public ArrayList<Pattern> patterns;
	private boolean matchfound;
	public Matcher(ArrayList<Pattern> p){
		patterns = p;
	}

	/**
	 * Performs one round of LR parsing per call of this method.
	 * <br>
	 * Will create matches until all are exhausted
	 * <BR>
	 * For future:
	 * Have a way to detec conflicting grammar rules. Copy the stack, and make the patterns match copies. If two patterns find a match on the same stack, then there is a conflict.
	 * @return The parse stack after one round of parsing.
	 */
	public ArrayList<ParseNode> match(ArrayList<ParseNode> stack, ParseNode lookahead){
		//System.out.println("Matcher received stack: "+stack+"; lookahead: "+lookahead);
		do{
			//System.out.println("Current Stack: "+stack+", look:"+lookahead);
			matchfound = false;
			for(int i = 0; i<patterns.size();i++){
				patterns.get(i).setMatcher(this);
				stack = patterns.get(i).match(stack,lookahead);
				if(matchfound){
					//System.out.println("Match found with: "+patterns.get(i).name);
					break;
					}
			}
			//if(matchfound){
			//}
		}while(matchfound);

		return stack;
	}

	public void matchFound(){
		matchfound=true;
	}

}
